import json

import pymysql
import traceback

# 断言
from config import BASE_PATH


def common_assert(resp, exp_status, exp_desc):
    resp_dict = resp.json()
    assert 200 == resp.status_code
    assert exp_status == resp_dict.get("status")
    assert exp_desc in resp_dict.get("description")


# 1.封装操作数据库的方法
def exe_sql(sql_str, db):
    conn = None
    cur = None
    try:
        # 2.创建数据库连接对象
        conn = pymysql.connect(host="121.43.169.97", user="student", password="P2P_student_2022", database=db)
        # 3.创建游标对象
        cur = conn.cursor()
        # 4.在游标对象中执行SQL语句
        cur.execute(sql_str)
        # 如果是查询语句
        if sql_str.split(" ")[0].lower() == "select":
            # 返回全部查询结果
            res = cur.fetchall()
            print(f"全部的查询结果:{res}")
            return res
        # 如果是非查询语句
        else:
            # 手动提交数据事务
            conn.commit()
            # 返回受影响的行数
            res = f"受影响的行数为{cur.rowcount}"
            print(res)
            return res
    except:
        # 有异常的情况下，进行数据库事务回滚
        if conn is not None:
            conn.rollback()
        traceback.print_exc()
    finally:
        # 5.关闭游标对象
        if cur is not None:
            cur.close()
        # 6.关闭数据库连接对象
        if conn is not None:
            conn.close()


# 封装清洗用户信息的方法    ,''
def clear_user_info():
    reg_mobile = "'18743264321','18743264122','18743264123','18743264124','18743264125','18743264126','18743264127','18743264128'"
    # 需要执行SQL语句
    sql1 = "delete i.* from mb_member_info i inner join mb_member m on m.id = i.member_id where m.phone in ({});".format(
        reg_mobile)
    sql2 = "delete l.* from mb_member_login_log l inner join mb_member m on m.id=l.member_id where m.phone in ({});".format(
        reg_mobile)
    sql3 = "delete from mb_member where phone in ({});".format(reg_mobile)
    sql4 = "delete from mb_member_register_log where phone in ({});".format(reg_mobile)
    # 调用封装操作数据库的方法，执行SQL语句
    exe_sql(sql1, "czbk_member")
    exe_sql(sql2, "czbk_member")
    exe_sql(sql3, "czbk_member")
    exe_sql(sql4, "czbk_member")


# 封装读取测试数据的方法
def read_json(filename, apiname):
    # 获取测试数据的文件路径
    file_path = BASE_PATH + "/data/" + filename + ".json"
    # 读取测试数据
    with open(file_path, encoding='utf-8') as f:
        # 将测试数据解析为字典类型
        data = json.load(f)
    # 获取指定接口的测试数据
    api_data = data.get(apiname)
    print(f"获取指定接口的测试数据:{api_data}")
    # 定义一个新的列表
    api_list = list()
    # 列表嵌套字典的测试数据转化为列表嵌套元组
    for api_dict in api_data:
        api_list.append(tuple(api_dict.values()))
    # 返回最新格式的测试数据
    print(f"最终的测试数据为：{api_list}")
    return api_list


# html解析工具
from bs4 import BeautifulSoup


def html_util(response):
    # 1.从响应结果中，获取请求的标签数据
    data = response.json().get("description").get("form")
    # 将获取的标签数据打印到日志
    print(f"获取标签格式的数据:{data}")
    # 2.创建beautifulsoup对象
    bs = BeautifulSoup(data, "html.parser")
    # 3.从form标签中获取url
    url = bs.form.get("action")
    # 4. 从input标签中获取请求体数据
    # 4.1 定义一个字典，用来接收请求体的数据
    form_dict = dict()
    # 4.2 获取全部的input标签
    input_all = bs.findAll("input")
    # 4.3 循环遍历出每一个input标签
    for input_sample in input_all:
        # 4.4从input标签中获取请求体的字段名
        key = input_sample.get("name")
        # 4.5从input标签中获取请求体的字段值
        value = input_sample.get("value")
        # 4.6.将字段名和值放入定义的请求体数据的字典中
        form_dict[key] = value
    # 将提取的请求数据(url和请求体数据)打印到日志
    print(f"提取第三方接口URL:{url},第三方请求体:{form_dict}")
    # 7.返回，带有url和请求体数据的列表
    return [url, form_dict]


if __name__ == '__main__':
    read_json("reg_login_data", "img_verify_code")
